var express = require('express')
var path = require('path')
var cookieParser = require('cookie-parser')
var logger = require('morgan')
const cors = require('cors')

var indexRouter = require('./routes/index')
var usersRouter = require('./routes/users')
const articleRouter = require('./routes/article')
const categoriesRouter = require('./routes/categories')
const echartsRouter = require('./routes/echarts')
const leavewordsRouter = require('./routes/leavewords')

var app = express()

app.use(cors())
app.use(logger('dev'))
app.use(express.json())
app.use(express.urlencoded({ extended: false }))
app.use(cookieParser())
app.use(express.static(path.join(__dirname, 'public')))

// 导入配置文件
const config = require('./routes/config.js')
// 解析 token 的中间件
var { expressjwt } = require('express-jwt')
// / 使用 .unless({ path: [/^\/user\//] }) 指定哪些接口不需要进行 Token 的身份认证
app.use(expressjwt({ secret: config.jwtSecretKey, algorithms: ['HS256'] }).unless({ path: [/^\/users\//] }))

app.use('/', indexRouter)
app.use('/users', usersRouter)
app.use('/article', articleRouter)
app.use('/categories', categoriesRouter)
app.use('/echarts', echartsRouter)
app.use('/BlogLeaveWords', leavewordsRouter)

//   捕获错误的路由需要放在所有路由的后面
app.use((err, req, res, next) => {
  if (err.name == 'UnauthorizedError') {
    res.send({
      status: 401,
      message: '无效的token...'
    })
  } else {
    next(err)
  }
})
module.exports = app
